package cn.kidng.gaodedemo;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements LocationSource, AMapLocationListener, Inputtips.InputtipsListener, PoiSearch.OnPoiSearchListener {

    private MapView mapView;
    private SearchView mSearchView;
    private ListView mLvSuggestion;

    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private String mCityCode;
    private String mLocationName;
    private TipsAdapter mTipsAdapter;
    private Inputtips mInputtips;
    private PoiSearch mPoiSearch;
    private PoiSearch.Query mPoiSearchQuery;
    private SuggestionAdapter mSuggestionAdapter;
    private AMapLocation currentLocation;
    private MyLocationStyle myLocationStyle;
    private PoiOverlay mPoiOverlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTitle();
        initSearchView();
        initAMap(savedInstanceState);
    }

    private void initSearchView() {
        mSearchView = (SearchView) findViewById(R.id.sv_search);
        mSearchView.setSubmitButtonEnabled(true);
        mSearchView.onActionViewExpanded();
        mInputtips = new Inputtips(this, this);
        mLvSuggestion = (ListView) findViewById(R.id.lv_suggestion);
        mPoiSearch = new PoiSearch(this, null);
        mPoiSearch.setOnPoiSearchListener(this);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                onGetInputtips(null, 0);
                if (mCityCode != null && mCityCode.length() != 0) {
                    mPoiSearchQuery = new PoiSearch.Query(query, null, mCityCode);
                } else {
                    mPoiSearchQuery = new PoiSearch.Query(query, null);
                }
                mPoiSearchQuery.setPageNum(0);//从0开始
                mPoiSearchQuery.setPageSize(20);//默认值是20 条,取值范围在1-30 条
                mPoiSearch.setQuery(mPoiSearchQuery);
                mPoiSearch.searchPOIAsyn();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText == null || newText.length() == 0) {
                    onGetInputtips(null, 0);
                    return true;
                }
                InputtipsQuery query = new InputtipsQuery(newText, mCityCode);
                mInputtips.setQuery(query);
                mInputtips.requestInputtipsAsyn();
                return true;
            }
        });
    }

    private void initTitle() {
//        mToolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(mToolbar);

    }

    /**
     * 初始化AMap对象
     *
     * @param savedInstanceState
     */
    private void initAMap(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
                if (marker.isInfoWindowShown()) {
                    marker.hideInfoWindow();
                } else {
                    marker.showInfoWindow();
                }
                return true;
            }
        });
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);

        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setScaleControlsEnabled(true);//设置显示地图的默认比例尺
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置默认缩放级别 3-19
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // aMap.setMyLocationType()
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (mlocationClient != null)
            mlocationClient.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mlocationClient != null)
            mlocationClient.stopLocation();
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            mLocationOption.setInterval(2000);
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                currentLocation = amapLocation;
                mCityCode = amapLocation.getCityCode();
                mLocationName = amapLocation.getCity() + amapLocation.getDistrict() + amapLocation.getStreet();
                setupTitleLocation();
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    private void setupTitleLocation() {
//        mTvLocation.setText(mLocationName);
        setTitle(mLocationName);
    }

    @Override
    public void onGetInputtips(List<Tip> list, int resultCode) {
        if (resultCode == 0 || list == null || list.isEmpty()) {
            mLvSuggestion.setVisibility(View.GONE);
            if (mTipsAdapter != null) mTipsAdapter.removeAll();
        } else {
            mLvSuggestion.setVisibility(View.VISIBLE);
            if (mTipsAdapter == null) {
                mTipsAdapter = new TipsAdapter(this, list);
                mTipsAdapter.setItemClickListener(new TipsAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, View view) {
                        mSearchView.setQuery(mTipsAdapter.getItem(position).getName(), false);
                    }
                });
                mLvSuggestion.setAdapter(mTipsAdapter);
            } else {
                mLvSuggestion.setAdapter(mTipsAdapter);
                mTipsAdapter.setList(list);
            }
        }
    }

    public void toPosition(int longitude, int latitude) {
        if (mapView != null) {

        }
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int resultCode) {
        if (resultCode == 0 || poiResult == null) {
            mLvSuggestion.setVisibility(View.GONE);
            if (mSuggestionAdapter != null) mSuggestionAdapter.removeAll();
            return;
        }
        mLvSuggestion.setVisibility(View.VISIBLE);
        ArrayList<PoiItem> list = poiResult.getPois();
        if (mPoiOverlay != null) {
            mPoiOverlay.removeFromMap();
        }
        mPoiOverlay = new PoiOverlay(aMap, list);
        mPoiOverlay.addToMap();
        mPoiOverlay.zoomToSpan();

        if (mSuggestionAdapter == null) {
            mSuggestionAdapter = new SuggestionAdapter(this, list);
            mSuggestionAdapter.setItemClickListener(new SuggestionAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position, View view) {
                    PoiItem item = mSuggestionAdapter.getItem(position);
                    LatLng latLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
                    for (Marker marker :
                            aMap.getMapScreenMarkers()) {
                        if (marker.getPosition().equals(latLng)) {
                            marker.showInfoWindow();
                        }
                    }
                }
            });
            mLvSuggestion.setAdapter(mSuggestionAdapter);
        } else {
            mLvSuggestion.setAdapter(mSuggestionAdapter);
            mSuggestionAdapter.setList(list);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int resultCode) {

    }
}
